package vn.bk.hotel;

import java.util.ArrayList;

import hust.sig.api.service.ImplementHotelService;
import vn.bk.hotel.global.Language;
import vn.bk.hotel.global.OnlineContentReader;
import vn.bk.hotel.global.Service;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;

public class SplashScreen extends Activity {

    private boolean isRunning;
    private int type;
    private String getServer;
    private ImageView numLoadImage;

    private LocationManager locationManager;
    private LocationListener locationListener;

    // GPS

    public static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in
    // Meters
    public static final long MINIMUM_TIME_BETWEEN_UPDATES = 1; // in

    public static double latitude = 21.02784;

    public static double longtitude = 105.852284;
    
    private final int REQUEST_CODE = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.splash_screen);
	numLoadImage = (ImageView) findViewById(R.id.numLoad);
	getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

    }

    @Override
    protected void onStart() {
	// TODO Auto-generated method stub
	super.onStart();

	Language.applySettingLanguage(this);
	Thread background = new Thread() {
	    @Override
	    public void run() {
		try {
		    for (int i = 0; i < 10 && isRunning; i++) {
			Thread.sleep(100);
		    }
		} catch (InterruptedException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		} finally {
		    runOnUiThread(new Runnable() {

			@Override
			public void run() {
			    // TODO Auto-generated method stub
			    new LoadHostFile().execute();
			}
		    });
		}
	    }
	};
	isRunning = true;
	background.start();
	final long timeStartLoad = System.currentTimeMillis();
	new Thread(new Runnable() {

	    @Override
	    public void run() {
		while (isRunning) {
		    final int numLoad = ((int) ((System.currentTimeMillis() - timeStartLoad) * 2.5 / 1000)) % 6;
		    runOnUiThread(new Runnable() {

			@Override
			public void run() {
			    // TODO Auto-generated method stub
			    numLoadImage.setImageResource(loadId(numLoad));
			}
		    });
		}
	    }
	}).start();
    }

    private int loadId(int number) {
	switch (number) {
	case 0:
	    return R.drawable.loading_0;
	case 1:
	    return R.drawable.loading_1;
	case 2:
	    return R.drawable.loading_2;
	case 3:
	    return R.drawable.loading_3;
	case 4:
	    return R.drawable.loading_4;
	case 5:
	    return R.drawable.loading_5;
	default:
	    return R.drawable.loading_5;
	}
    }

    @Override
    protected void onStop() {
	// TODO Auto-generated method stub
	super.onStop();
	isRunning = false;
    }

    @Override
    protected void onPause() {
	// TODO Auto-generated method stub
	super.onPause();	
	try {
	    locationManager.removeUpdates(locationListener);
	} catch (Exception e) {
	    // TODO: handle exception
	}
	finish();
    }

    public class GetListCity extends AsyncTask<Void, Integer, String> {

	private boolean find = true;

	@SuppressWarnings("deprecation")
	@Override
	protected String doInBackground(Void... params) {

	    try {
		ImplementHotelService localImplementHotelService = Service
			.getHotelService();

		localImplementHotelService.getAllProvinceAndCity();

		localImplementHotelService.getAllCity(Language
			.getLanguage(SplashScreen.this));

		return null;
	    } catch (Exception localException) {
		find = false;
	    }
	    return null;
	}

	@Override
	protected void onPostExecute(String result) {
	    // TODO Auto-generated method stub
	    super.onPostExecute(result);

	    if (this.find) {

		// startActivity(new Intent(SplashScreen.this,
		// MainMenuActivity.class));
		((TextView) findViewById(R.id.status_load)).setText(getString(R.string.status_load_location));
		detectLocation();
	    } else {
		if (type == 1) {
		    showNotificationDialog();
		} else {
		    Service.ipServer = getServer;
		    type = 1;
		    new GetListCity().execute();
		}

	    }
	}

    }

    public void detectLocation() {
	locationManager = (LocationManager) this
		.getSystemService(Context.LOCATION_SERVICE);

	locationListener = new LocationListener() {

	    @Override
	    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {

	    }

	    @Override
	    public void onProviderEnabled(String arg0) {
	    }

	    @Override
	    public void onProviderDisabled(String arg0) {
		Log.i("TAG", "PROVIDER DISABLE");
	    }

	    @Override
	    public void onLocationChanged(Location location) {
		Log.i("TAG", String.valueOf(location.getLatitude()));
		setGeoLocation(location);
	    }

	};

	// locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
	// MINIMUM_TIME_BETWEEN_UPDATES,
	// MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
	if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {

	    findNetwork();

	} else if (locationManager
		.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
	    findGPS();
	} else {

	    promptSetLocationSettings();

	}
    }

    private void findNetwork() {
	Log.i("LOCATION", "NETWORK");
	try {
	    locationManager.requestLocationUpdates(
		    LocationManager.NETWORK_PROVIDER,
		    MINIMUM_TIME_BETWEEN_UPDATES,
		    MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
	    // Location lastKnowLocation = locationManager
	    // .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
	    // if (lastKnowLocation != null) {
	    // setGeoLocation(lastKnowLocation);
	    // } else {
	    //
	    // if (locationManager
	    // .isProviderEnabled(LocationManager.GPS_PROVIDER)) {
	    //
	    // findGPS();
	    // } else {
	    // Toast.makeText(MainMenuActivity.this,
	    // getString(R.string.get_location_default),
	    // Toast.LENGTH_SHORT).show();
	    //
	    // }
	    // }
	} catch (IllegalArgumentException e) {
	    e.printStackTrace();
	    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {

		findGPS();
	    } else {
		Toast.makeText(SplashScreen.this,
			getString(R.string.get_location_default),
			Toast.LENGTH_SHORT).show();

	    }
	}
    }

    private void findGPS() {
	Log.i("LOCATION", "GPS");
	try {
	    locationManager.requestLocationUpdates(
		    LocationManager.GPS_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES,
		    MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, locationListener);

	    // Location lastKnowLocation = locationManager
	    // .getLastKnownLocation(LocationManager.GPS_PROVIDER);
	    // if (lastKnowLocation != null) {
	    // Log.v("TEST", "last lat: " + lastKnowLocation.getLatitude());
	    // setGeoLocation(lastKnowLocation);
	    //
	    // } else {
	    //
	    // Toast.makeText(MainMenuActivity.this,
	    // getString(R.string.get_location_default),
	    // Toast.LENGTH_SHORT).show();
	    //
	    // }
	} catch (IllegalArgumentException e) {
	    Toast.makeText(SplashScreen.this,
		    getString(R.string.get_location_default),
		    Toast.LENGTH_SHORT).show();
	}
    }

    private void promptSetLocationSettings() {
	AlertDialog.Builder dialog = new AlertDialog.Builder(
		SplashScreen.this);
	dialog.setTitle(getString(R.string.dialog_setting_location_title));
	dialog.setMessage(getString(R.string.dialog_setting_location_message));
	dialog.setNegativeButton(
		getString(R.string.dialog_setting_location_button_ok),
		new DialogInterface.OnClickListener() {

		    @Override
		    public void onClick(DialogInterface dialog, int which) {

		    }
		});
	dialog.setPositiveButton(
		getString(R.string.dialog_setting_location_button_setting),
		new DialogInterface.OnClickListener() {

		    @Override
		    public void onClick(DialogInterface dialog, int which) {
			enableLocationSettings();
		    }
		});
	dialog.setCancelable(false);
	dialog.show();
    }

    private void enableLocationSettings() {
	Intent settingsIntent = new Intent(
		Settings.ACTION_LOCATION_SOURCE_SETTINGS);
	startActivityForResult(settingsIntent, REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent arg2) {
	// TODO Auto-generated method stub
	super.onActivityResult(requestCode, resultCode, arg2);
	Log.i("REQUEST CODE", String.valueOf(requestCode));
	Log.i("RESULT CODE", String.valueOf(resultCode));

	if (requestCode == REQUEST_CODE) {
	    if (resultCode == 0) {
		Log.i("tag", "Start detect");
		detectLocation();
	    }
	}
    }

    private void setGeoLocation(Location location) {
	latitude = location.getLatitude();
	longtitude = location.getLongitude();
	Log.i("Location", "Latitude : " + String.valueOf(latitude)
		+ "\nLongitude : " + String.valueOf(longtitude));
	startActivity(new Intent(this, MainMenuActivity.class));
    }

    private void showNotificationDialog() {
	AlertDialog.Builder dialog = new AlertDialog.Builder(SplashScreen.this);
	dialog.setTitle(getString(R.string.error_connect_dialog_title));
	dialog.setMessage(getString(R.string.error_connect_dialog_message));
	dialog.setNegativeButton(getString(R.string.error_connect_dialog_exit),
		new DialogInterface.OnClickListener() {
		    public void onClick(
			    DialogInterface paramAnonymousDialogInterface,
			    int paramAnonymousInt) {
			finish();
		    }
		});
	dialog.setPositiveButton("Retry", new OnClickListener() {

	    @Override
	    public void onClick(DialogInterface dialog, int which) {

		new LoadHostFile().execute();
	    }
	});
	dialog.setCancelable(false);
	dialog.show();
    }

    class LoadHostFile extends AsyncTask<Void, Void, Void> {

	private ArrayList<String> listHostContentStrings;

	@Override
	protected Void doInBackground(Void... params) {
	    listHostContentStrings = new OnlineContentReader()
		    .getStringArrayFromURL("https://sites.google.com/site/diemdenviet/newhost.txt");

	    return null;
	}

	@Override
	protected void onPostExecute(Void result) {
	    try {
		if (listHostContentStrings != null
			&& listHostContentStrings.get(1).equals("1")) {
		    Service.ipServer = listHostContentStrings.get(0);
		    type = 1;
		    new GetListCity().execute();
		} else {
		    Service.ipServer = Service.currentServer;
		    type = 0;
		    getServer = listHostContentStrings.get(0);
		    new GetListCity().execute();
		}

	    } catch (IndexOutOfBoundsException e) {
		showNotificationDialog();
	    }

	}

    }

}
